<template>
  <div>
    <el-form ref="form" :model="formData" label-width="100px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" placeholder="" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" placeholder="" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" placeholder="请选择" style="width:100%">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          type="textarea"
          :rows="3"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { queryDepartment, reqGetEmployeeSimple } from '@/api/departments'
import { validDpt } from '@/utils/validate'
export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    const dptName = (rule, value, callback) => {
      if (!validDpt(value, 'name')) return callback(new Error('部门名称重复'))
      callback()
    }
    const dptCode = (rule, value, callback) => {
      if (!validDpt(value, 'code')) return callback(new Error('部门代码重复'))
      callback()
    }
    return {
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' },
          { trigger: 'blur', validator: dptName }],
        code: [{ required: true, message: '请输入部门名称', trigger: 'blur' },
          { trigger: 'blur', validator: dptCode }],
        manager: [{ required: true, message: '请输选择部门负责人', trigger: 'blur' }],
        introduce: [{ required: true, message: '请输入部门介绍', trigger: 'blur' }]
      },
      options: []
    }
  },

  mounted() {
    this.reqGetEmployeeSimple()
    if (this.type === 'edit') {
      this.queryDepartment()
    } else {
      this.$set(this.formData, 'pid', this.id)
    }
  },

  methods: {
    async queryDepartment() {
      const { data } = await queryDepartment(this.id)
      this.formData = data
    },
    async  reqGetEmployeeSimple() {
      const { data } = await reqGetEmployeeSimple()
      this.options = data
    },
    async validForm() {
      try {
        await this.$refs.form.validate()
      } catch (error) {
        // throw new Error('校验失败')
        return Promise.reject('校验未通过')
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
